package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.config.annotation.Service;
import com.mongodb.client.result.UpdateResult;
import com.tanhua.dubbo.server.pojo.UserLocation;
import com.tanhua.dubbo.server.vo.UserLocationVo;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@Service(version = "1.0.0")
public class UserLocationApiImpl implements UserLocationApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 新增获取跟新userLocation表.返回特有的id
     * @param userId 当前登录用户id
     * @param longitude  经度
     * @param latitude  纬度
     * @param address 位置信息
     * @return
     */
    @Override
    public String updateUserLocation(Long userId, Double longitude, Double latitude, String address) {

        UserLocation userLocation = new UserLocation();
        userLocation.setAddress(address); //地址
        userLocation.setLocation(new GeoJsonPoint(longitude, latitude)); //坐标
        userLocation.setUserId(userId); //用户ID

        Query query = Query.query(Criteria.where("userId").is(userLocation.getUserId()));
        //从mongoDb中查UserLocation表
        UserLocation ul = this.mongoTemplate.findOne(query, UserLocation.class);
        //如果查找的为空就新增
        if (ul == null) {
            //新增
            userLocation.setId(ObjectId.get());
            userLocation.setCreated(System.currentTimeMillis());//创建时间
            userLocation.setUpdated(userLocation.getCreated());//上次跟新时间和创建时间保持一致
            userLocation.setLastUpdated(userLocation.getCreated());//更新时间和创建时间保持一致

            //存入表中
            this.mongoTemplate.save(userLocation);
            /*if (save==null){
                return false;
            }else{
                return true;
            }*/

            //返回地址位置id
            return userLocation.getId().toHexString();
        } else {
            //更新
            Update update = Update
                    .update("location", userLocation.getLocation())
                    .set("updated", System.currentTimeMillis())
                	.set("address", userLocation.getAddress())
                    .set("lastUpdated", ul.getUpdated());//上次修改时间为获取的ul对象的更新时间
            this.mongoTemplate.updateFirst(query, update, UserLocation.class);

        }

        return ul.getId().toHexString();
    }

    /**
     * 根据用户id查询位置
     * @param userId UserLocationVo
     * @return
     */
    @Override
    public UserLocationVo queryByUserId(Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        UserLocation userLocation = this.mongoTemplate.findOne(query, UserLocation.class);
        return UserLocationVo.format(userLocation);
    }

    /**
     * 查找附近的用户
     * @param longitude 经度
     * @param latitude 纬度
     * @param range 范围
     * @return
     */
    @Override
    public List<UserLocationVo> queryUserFromLocation(Double longitude, Double latitude, Integer range) {

        //中心点
        GeoJsonPoint geoJsonPoint = new GeoJsonPoint(longitude, latitude);

        //画圈的半径
        Distance distance = new Distance(range / 1000, Metrics.KILOMETERS);

        //根据中心点和半径画一个圆
        Circle circle = new Circle(geoJsonPoint, distance);
        //条件:location=画的圆
        Query query = Query.query(Criteria.where("location").withinSphere(circle));

        return UserLocationVo.formatToList(this.mongoTemplate.find(query, UserLocation.class));
    }

}
